package xl.net
{
	import com.adobe.serialization.json.JSON;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.NetConnection;
	import flash.net.Responder;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	import xl.utils.I18n;

	public class HttpConnect
	{
		private var _yiiWay:String = 'http://www.srcms.com/index.php';
		private var _connect:URLLoader = new URLLoader();
		private var _request:URLRequest = new URLRequest();
		private var _currentModel:HttpModel;
		

		public function HttpConnect()
		{
			_connect = new URLLoader();
			_request.method = URLRequestMethod.POST;
			_connect.addEventListener(Event.COMPLETE,onCompleteCall);
			_connect.addEventListener(IOErrorEvent.IO_ERROR,onFaultCall);
		}
		
		public function call($model:HttpModel):void
		{
			_currentModel = $model;
			if(_currentModel.url)
			{
				_request.url = _currentModel.url+'&clientId='+$model.id;
			}
			else
			{
				_request.url = _yiiWay+"?r="+_currentModel.controller+"/"+_currentModel.action+'&clientId='+$model.id;
			}
			
			_request.data = getVariable($model.param);
			_connect.load(_request);
		}
		
		private function getVariable(_param:Object):URLVariables
		{
			var _variable:URLVariables = new URLVariables();
			for(var k:String in _param)
			{
				_variable[k] = _param[k];
			}
			_variable['client'] = 'flash';
			return _variable;
		}
		
		private function onCompleteCall(evt:Event):void
		{
			if(_currentModel.okCall!=null)
			{
				var _data:Object = JSON.decode(evt.target.data);
				if(_data)
				{
					var errorCode:int = _data['errorCode']>>0;
					if(errorCode)
					{
						_data['errorMsg'] = I18n.getLocaleStr("error"+errorCode);
						onError(_data);
						return;
					}
				}
				_currentModel.okCall.call(null,_data);
			}
		}
		
		private function onError($data:Object):void
		{
			if(_currentModel.faultCall!=null)
			{
				_currentModel.faultCall.call(null,$data);
			}			
		}
		
		private function onFaultCall(evt:Event):void
		{
			if(_currentModel.faultCall!=null)
			{
				_currentModel.faultCall.call(null,evt.target.data);
			}				
		}
		
	}
}